// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let { OPENID, APPID, UNIONID } = wxContext
  let { cardId, avatarUrl, nickName} = event
  var success = false
  var cancel = false
  var message = "点赞失败"
  console.log('cardId:'+cardId)
  const db = cloud.database()
  const _ = db.command
  var likeData = await db.collection('like-list').where({
    _openid: OPENID,// 填入当前用户 openid
    cardId: cardId
  }).get()

  if (likeData.data.length != 0) {
    var likeData = await db.collection('like-list').where({
      _openid: OPENID,// 填入当前用户 openid
      cardId: cardId
    }).remove().then(res => {
      success = true
      cancel = true
      message = "取消点赞成功"

      db.collection('cards').where({
        _id: cardId
      }).update({
        data: {
          likeNo: _.inc(-1)
        }
      })
    }, error => {
      success = false
      cancel = true
      message = "取消点赞失败"
    })
  } else {
    let systemTime = new Date().getTime()
    var likeData = await db.collection('like-list').add({
      data: {
        _openid: OPENID,
        cardId: cardId,
        avatarUrl:avatarUrl,
        nickName:nickName,
        systemTime:systemTime
      }
    }).then(res => {
      success = true
      cancel = false
      message = "点赞成功"
      db.collection('cards').where({
        _id: cardId
      }).update({
        data: {
          likeNo: _.inc(1)
        }
      })
    }, error => {
      success = false
      cancel = false
      message = "点赞失败"
    })
  }
  return {
    success: success,
    cancel:cancel,
    message: message
  }
}